<?php
declare (strict_types=1);

namespace app\listener;

use app\common\job\SmsConsultingServer;
use app\common\model\Consulting;
use app\common\model\ConsultingMessage;
use app\common\service\GatewayClientServer;
use think\facade\Queue;

class ConsultingMessageCreated
{
    /**
     * 消息创建 事件监听处理
     *
     * @return mixed
     */
    public function handle($params)
    {
        $consulting = $params['consulting'] ?? null;
        $message = $params['message'] ?? null;

        // 消息创建后

        // 更新活动时间
        $lastActiveTime = $message->messageTime / 1000 + 24 * 3600;
        $consulting->updateActiveTime($lastActiveTime);

        // 更新咨询上的最新消息时间
        Consulting::update([
            'lastChatTime' => $message->messageTime,
        ], fn($query) => $query->where('id', $message->consultingId));

        // 如果是服务卡片消息
        if($message->messageType == ConsultingMessage::SERVER ){
            // 免费咨询，就更新前端咨询模型
            if($consulting->consultingType == 0){
                event('ConsultingUpdated', $consulting);
            }

            // 添加任务1分钟后没有付款，就发短信
            $job_data = ['id' => $consulting->id];
            Queue::later(60, SmsConsultingServer::class, $job_data);
        }

        // 消息创建后，给双方发咨询列表更新推送
        $data = [
            'action' => CHAT_LIST,
            'data' => [],
        ];
        if (is_id($consulting->memberId)) {
            $this->getGatewayClientServer()->sendToUid($consulting->memberId, json_encode($data));
        }
        if (is_id($consulting->lawyerId)) {
            $this->getGatewayClientServer()->sendToUid($consulting->lawyerId, json_encode($data));
        }

        // 给双方发红点更新推送
        $data = [
            'action' => REDDOT,
            'data' => [],
        ];
        if (is_id($consulting->memberId)) {
            $this->getGatewayClientServer()->sendToUid($consulting->memberId, json_encode($data));
        }
        if (is_id($consulting->lawyerId)) {
            $this->getGatewayClientServer()->sendToUid($consulting->lawyerId, json_encode($data));
        }

    }

    private function getGatewayClientServer(): GatewayClientServer
    {
        return app(GatewayClientServer::class);
    }
}
